package online.longzipeng.cinemasys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import online.longzipeng.cinemasys.common.result.ResponseEnum;
import online.longzipeng.cinemasys.common.result.Result;
import online.longzipeng.cinemasys.common.utils.ExceptionUtils;
import online.longzipeng.cinemasys.common.utils.Md5Utils;
import online.longzipeng.cinemasys.config.JWTConfig;
import online.longzipeng.cinemasys.dto.sysuser.SysUserLoginResponseDTO;
import online.longzipeng.cinemasys.dto.sysuser.SysUserQueryResponseDTO;
import online.longzipeng.cinemasys.entity.SysUser;
import online.longzipeng.cinemasys.mapper.SysUserMapper;
import online.longzipeng.cinemasys.service.SysUserService;
import online.longzipeng.cinemasys.vo.sysuser.SysUserChangePasswordVo;
import online.longzipeng.cinemasys.vo.sysuser.SysUserQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * <p>
 *  系统用户服务实现类
 * </p>
 *
 * @author lzp
 * @since 2021-04-09
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    JWTConfig jwtConfig;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    RedisTemplate redisTemplate;

    private static final  String USER_KEY = "sysUser_";

    @Override
    public SysUserLoginResponseDTO login(SysUser loginSysUser) {
        // 用户账号密码校验
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
        queryWrapper.eq("user_name",loginSysUser.getUserName());
        SysUser sysUser = getOne(queryWrapper);
        // 用户不存在或密码错误判断
        ExceptionUtils.isNotNull(sysUser, ResponseEnum.USER_LOGIN_ERROR,null);
        ExceptionUtils.isTrue(Md5Utils.checkPassword(loginSysUser.getPassword(),sysUser.getPassword()),
                ResponseEnum.USER_LOGIN_ERROR,null);
        // 用户状态判断
        if (!sysUser.getStatus().equals(1)) {
            ExceptionUtils.isTrue(!sysUser.getStatus().equals(2),new Result("750","用户已被锁住！！请重置密码！！",null));
            ExceptionUtils.isTrue(!sysUser.getStatus().equals(1),new Result("750","用户已被禁用！！请通知管理员解决限制！！",null));
        }
        // 更新用户的最后登录时间和ip
        sysUser.setLastLoginTime(LocalDateTime.now());
        sysUser.setLastLoginIp(loginSysUser.getLastLoginIp());
        updateById(sysUser);
        // 生成token
        SysUserLoginResponseDTO sysUserLoginResponseDTO = new SysUserLoginResponseDTO(sysUser.getId(),sysUser.getNick(),
                sysUser.getAvatar(), sysUser.getLastLoginTime(),sysUser.getLastLoginIp(),null);
        sysUserLoginResponseDTO.setToken(jwtConfig.generateJwtAdmin(sysUserLoginResponseDTO));
        redisTemplate.opsForValue().set(USER_KEY+sysUser.getUserName(), JSON.toJSONString(sysUserLoginResponseDTO),15);
        return sysUserLoginResponseDTO;
    }

    @Override
    public void changePassword(SysUserChangePasswordVo sysUserChangePasswordVo) {
        // 修改密码
        SysUser sysUser = getById(sysUserChangePasswordVo.getId());
        ExceptionUtils.isNotNull(sysUser,"用户不存在！！");
        ExceptionUtils.isTrue(Md5Utils.checkPassword(sysUserChangePasswordVo.getOldPassword(),sysUser.getPassword()),
                "旧密码输入错误！！");
        sysUser.setPassword(Md5Utils.encrypt(sysUserChangePasswordVo.getNewPassword()));
        updateById(sysUser);
    }

    @Override
    public void add(SysUser sysUser) {
        // 加密
        sysUser.setPassword(Md5Utils.encrypt(sysUser.getPassword()));
        save(sysUser);
    }

    @Override
    public void updateUser(SysUser sysUser) {
        String userName = sysUser.getUserName();
        if (!StringUtils.isEmpty(userName) && !userName.equals(getById(sysUser.getId()).getUserName())) {
            // 用户账号密码校验
            ExceptionUtils.isNull(findByUserName(userName), ResponseEnum.USER_EXISTED,null);
        }
        // 更新
        updateById(sysUser);
    }

    @Override
    public SysUserLoginResponseDTO getInfo(String token) {
        return jwtConfig.checkJwtAdmin(token);
    }

    @Override
    public IPage<SysUserQueryResponseDTO> getListPage(SysUserQueryVO sysUserQueryVO) {
        Page<SysUserQueryResponseDTO> queryPage = new Page<>(sysUserQueryVO.getPage(),sysUserQueryVO.getSize());
        QueryWrapper<SysUserQueryResponseDTO> qwSysUser = new QueryWrapper<>();
        // 先判断查询类型 判断查询条件 用户名 昵称  状态 排序
        if (sysUserQueryVO.getSearchType()) {
            qwSysUser.like(!StringUtils.isEmpty(sysUserQueryVO.getUserName()),"user_name",sysUserQueryVO.getUserName());
            qwSysUser.like(!StringUtils.isEmpty(sysUserQueryVO.getNick()),"nick",sysUserQueryVO.getNick());
            qwSysUser.eq(!StringUtils.isEmpty(sysUserQueryVO.getStatus()),"status",sysUserQueryVO.getStatus());
        }else {
            qwSysUser.or().like(!StringUtils.isEmpty(sysUserQueryVO.getUserName()),"user_name",sysUserQueryVO.getUserName());
            qwSysUser.or().like(!StringUtils.isEmpty(sysUserQueryVO.getNick()),"nick",sysUserQueryVO.getNick());
            qwSysUser.or().eq(!StringUtils.isEmpty(sysUserQueryVO.getStatus()),"status",sysUserQueryVO.getStatus());
        }
        // 判断排序
        if ("desc".equals(sysUserQueryVO.getSort())) {
            qwSysUser.orderByDesc("id");
        }else {
            qwSysUser.orderByAsc("id");
        }
        return sysUserMapper.getListPage(queryPage,qwSysUser);
    }

    @Override
    public SysUser getUserInfo(String token) {
        SysUserLoginResponseDTO sysUserLoginResponseDTO = jwtConfig.checkJwtAdmin(token);
        return getById(sysUserLoginResponseDTO.getId());
    }

    @Override
    public SysUser findByUserName(String userName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        return getOne(queryWrapper);
    }
}
